const express = require('express');
const mysql = require('mysql');
const JWT = require('jsonwebtoken');
const expressJWT = require('express-jwt');
const cors = require('cors');
const secretKey = 'sun string ^_^';

let connection = mysql.createConnection({
  host: '192.168.61.128',
  password: '123456',
  user: 'master',
  database: 'kangyi',
});
connection.connect();

let app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.use(
  expressJWT({
    secret: secretKey,
  }).unless({
    path: [
      '/login',
      '/register',
      '/search',
      '/getvideoinfo',
      '/gettimedata',
      '/gettimeinfo',
    ],
  })
);
app.use((err, req, res, next) => {
  if (err.name == 'UnauthorizedError') {
    return res.send({ message: 'token失效' });
  } else {
    next();
  }
});
// 注册接口
app.post('/register', (req, res) => {
  let name = req.body.name;
  let pwd = req.body.pwd;
  let sql = `insert into users(name,pwd) values('${name}','${pwd}');`;
  connection.query(sql, (err, data) => {
    if (err) {
      res.send('error is' + err);
      return;
    } else {
      res.send({ message: 'ok' });
      return;
    }
  });
});

// 获取用户信息
app.post('/getuser', (req, res) => {
  let token = req.headers['authorization'];
  if (!token) {
    return res.send({ message: '无用户数据' });
  } else {
    let u_id = JWT.verify(token.split(' ')[1], secretKey).userid;
    let sql = `select id,name,u_img from users where id=${u_id};`;
    connection.query(sql, (err, data) => {
      if (err) {
        res.send('err' + err);
        return;
      } else {
        res.send({ message: 'ok', data: data[0], token: token });
        return;
      }
    });
  }
});
// 登录接口
app.post('/login', (req, res) => {
  let name = req.body.name;
  let pwd = req.body.pwd;
  let sql = `select id,name,u_img from users where name='${name}' and pwd='${pwd}';`;
  connection.query(sql, (err, data) => {
    if (err) {
      res.send('error is' + err);
      return;
    } else if (data.length == 0) {
      res.send({ status: '200', message: '无查询结果', data });
      return;
    } else {
      let tokens = JWT.sign({ userid: data[0].id }, secretKey, {
        expiresIn: '24h',
      });

      res.send({
        message: 'ok',
        data: data[0],
        token: tokens,
      });
      return;
    }
  });
});

// search
app.post('/search', (req, res) => {
  let search = req.body.search;
  let u_id = req.body.userid;
  let sql, userid;
  let token = req.headers['authorization'];
  if (token.length < 5) {
    userid = '';
  } else {
    userid = JWT.verify(token.split(' ')[1], secretKey).userid;
  }
  if (u_id == '') {
    sql = `SELECT * FROM videos where title like "%${search}%";`;
  } else {
    sql = `select * from videos right join (select v_id from sc where u_id='${userid}') as t1 on videos.id=t1.v_id`;
  }
  connection.query(sql, (err, data) => {
    if (err) {
      res.send('err' + err);
      return;
    } else {
      res.send({ status: 200, msg: 'ok', data });
      return;
    }
  });
});

// 请求video详情
app.post('/getvideoinfo', (req, res) => {
  let vid = req.body.videoid;
  let getvideosql = `select * from videos where id=${vid}`;
  let getplsql = `select users.name,users.u_img,pl.content from pl left join users on pl.u_id=users.id where pl.v_id=${vid};`;
  let getvlist = `select * from videos where id!=${vid}`;

  let data = {
    message: 'ok',
    data: { videoinfo: '', pllist: '', videolist: '' },
  };
  connection.query(getvideosql, (err, resdata) => {
    if (err) {
      console.log('err' + err);
      res.send({ message: '出错了' });
      return;
    } else {
      data.data.videoinfo = resdata[0];
      connection.query(getplsql, (err, resdata) => {
        if (err) {
          console.log('err' + err);
          res.send({ message: '出错了' });
          return;
        } else {
          data.data.pllist = resdata;
          connection.query(getvlist, (err, resdata) => {
            if (err) {
              console.log('err' + err);
              res.send({ message: '出错了' });
              return;
            } else {
              data.data.videolist = resdata;
              res.send(data);
              return;
            }
          });
        }
      });
    }
  });
});
// 获取点赞信息
app.post('/z', (req, res) => {
  let vid = req.body.videoid;
  let token = req.headers['authorization'];
  let u_id = JWT.verify(token.split(' ')[1], secretKey).userid;
  let getz = `select * from dz where u_id=${u_id} and v_id=${vid}`;
  connection.query(getz, (err, resdata) => {
    if (err) {
      console.log('err' + err);
      res.send({ message: '出错了' });
      return;
    } else if (resdata.length) {
      res.send(true);
      return;
    } else {
      res.send(false);
      return;
    }
  });
});
// 获取收藏信息
app.post('/getsc', (req, res) => {
  let vid = req.body.videoid;
  let token = req.headers['authorization'];
  let u_id = JWT.verify(token.split(' ')[1], secretKey).userid;
  let getz = `select * from sc where u_id=${u_id} and v_id=${vid}`;
  connection.query(getz, (err, resdata) => {
    if (err) {
      console.log('err' + err);
      res.send({ message: '出错了' });
      return;
    } else if (resdata.length) {
      res.send(true);
      return;
    } else {
      res.send(false);
      return;
    }
  });
});
// 收藏请求
app.post('/sc', (req, res) => {
  let videoid = req.body.videoid;
  let statu = Boolean(JSON.parse(req.body.statu));
  let token = req.headers['authorization'];
  let userid;
  if (!token) {
    return res.send({ message: '无用户数据' });
  } else {
    userid = JWT.verify(token.split(' ')[1], secretKey).userid;
  }
  let sql;
  if (statu) {
    sql = `insert into sc(u_id,v_id) value(${userid},${videoid});`;
  } else {
    sql = `DELETE FROM sc WHERE (u_id = ${userid} and v_id=${videoid});`;
  }
  connection.query(sql, (err, data) => {
    if (err) {
      return res.send({ message: 'err', data: 'err' + err });
    } else {
      return res.send({ status: 200, message: 'ok' });
    }
  });
});
// 点赞请求
app.post('/dz', (req, res) => {
  let videoid = req.body.videoid;
  let statu = Boolean(JSON.parse(req.body.statu));
  let token = req.headers['authorization'];
  let userid, v, dzsql;
  if (!token) {
    return res.send({ message: '无用户数据' });
  } else {
    userid = JWT.verify(token.split(' ')[1], secretKey).userid;
  }

  let sql = `select z_num from videos where id=${videoid};`;
  connection.query(sql, (err, data) => {
    if (err) {
      res.send('err' + err);
      return;
    } else {
      if (statu) {
        v = data[0].z_num + 1;
      } else {
        v = data[0].z_num - 1;
      }
      let sql = `UPDATE videos SET z_num = ${v} WHERE (id = ${videoid});`;
      connection.query(sql, (err, data) => {
        if (err) {
          res.send('err' + err);
          return;
        } else {
          if (statu) {
            dzsql = `insert into dz(u_id,v_id) value(${userid},${videoid});`;
          } else {
            dzsql = `DELETE FROM dz WHERE (u_id = ${userid} and v_id=${videoid});`;
          }
          connection.query(dzsql, (err, data) => {
            if (err) {
              return res.send({ message: 'err', data: 'err' + err });
            } else {
              return res.send({ status: 200, message: 'ok' });
            }
          });
        }
      });
    }
  });
});

// 获取时间轴数据
app.get('/gettimedata', (req, res) => {
  let sql = `select * from timedata`;
  connection.query(sql, (err, data) => {
    if (err) {
      return res.send('err' + err);
    } else {
      return res.send(data);
    }
  });
});

// 搜索具体日子
app.get('/gettimeinfo', (req, res) => {
  let time = req.query.time;
  let sql = `select id from timedata where time='${time}'`;
  connection.query(sql, (err, data) => {
    if (err) {
      return res.send('err' + err);
    } else {
      return res.send(data[0]);
    }
  });
});
// 评论请求
app.post('/updatepl', (req, res) => {
  let content = req.body.content;
  let vid = req.body.videoid;
  let userid;
  let token = req.headers['authorization'];
  if (!token) {
    return res.send({ message: '无用户数据' });
  } else {
    userid = JWT.verify(token.split(' ')[1], secretKey).userid;
  }
  let sql = `INSERT INTO pl (u_id, v_id, content) VALUES (${userid}, ${vid},  '${content}');`;
  connection.query(sql, (err, data) => {
    if (err) {
      return res.send('err' + err);
    } else {
      let getusersql = `select users.name,users.u_img from users where id=${userid};`;
      connection.query(getusersql, (err, data) => {
        if (err) {
          return res.send('err' + err);
        } else {
          return res.send({ message: 'ok', user: data[0] });
        }
      });
    }
  });
});

//增加播放量
app.post('/addplaynum', (req, res) => {
  let v_id = req.body.videoid;
  let searchvideosql = `select p_num from videos where id=${v_id}`;
  connection.query(searchvideosql, (err, data) => {
    if (err) {
      return res.send({ message: 'not ok', data: 'err' + err });
    } else {
      let p_num = data[0].p_num + 1;
      let addnumsql = `UPDATE videos SET p_num = ${p_num} WHERE (id = ${v_id});`;
      connection.query(addnumsql, (err, data) => {
        if (err) {
          return res.send({ message: 'not ok', data: 'err' + err });
        } else {
          return res.send({ message: 'ok', data });
        }
      });
    }
  });
});

app.get('/', (req, res) => {
  res.send('哈喽！');
});
app.listen(8000, (err, res) => {
  console.log('server is running http://127.0.0.1:8000');
});
